package com.neusoft.neuiotms.dcam.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.common.converter.ManufacturerConverter;
import com.neusoft.neuiotms.dcam.common.dto.ManufacturerDTO;
import com.neusoft.neuiotms.dcam.common.model.Manufacturer;
import com.neusoft.neuiotms.dcam.common.repository.ManufacturerRepository;
import com.neusoft.neuiotms.dcam.common.service.ManufacturerService;
import com.neusoft.neuiotms.dcam.common.vo.ManufacturerImportVO;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ManufacturerServiceImpl implements ManufacturerService {

    @Autowired
    private ManufacturerConverter manufacturerConverter;
    @Autowired
    private ManufacturerRepository manufacturerRepository;
    //    @Autowired
    //    private AssetService assetService;

    @Override
    public List<ManufacturerDTO> findAll() {
        final List<Manufacturer> models = this.manufacturerRepository.findAll();
        return this.manufacturerConverter.toListDTO(models);
    }

    @Override
    public Page<ManufacturerDTO> search(final Pageable pageable, final Searchable searchable) {
        final Page<Manufacturer> models = this.manufacturerRepository.search(pageable, searchable);
        final Page<ManufacturerDTO> dtos = this.manufacturerConverter.toPageDTO(models);
        return dtos;
    }

    @Override
    public ManufacturerDTO create(final ManufacturerDTO dto) {

        final Manufacturer model = this.manufacturerConverter.toModel(dto);
        this.manufacturerRepository.save(model);

        return this.manufacturerConverter.toDTO(model);
    }

    @Override
    public ManufacturerDTO details(final Long id) {

        final Manufacturer model;
        try {
            model = this.manufacturerRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        return this.manufacturerConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {
        //        final Searchable searchable = new Searchable();
        //        searchable.put("manufacturerId", id);
        //        final Page<AssetDTO> assets = this.assetService.search(Pageable.unpaged(), searchable);
        //        if (assets.getTotalElements() > 0) {
        //            throw new UnitedException("此供应商节点已有资产，请先删除资产", new Object[] {id });
        //        }
        //        try {
        //        } catch (final Exception e) {
        //            throw new UnitedException("此供应商已经绑定了业务,不能被删除", new Object[] {id });
        //        }
        this.manufacturerRepository.deleteById(id);

    }

    @Override
    public ManufacturerDTO update(final Long id, final ManufacturerDTO dto) {

        Manufacturer model;
        try {
            model = this.manufacturerRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.manufacturerConverter.toModel(dto);
        this.manufacturerRepository.save(model);

        return this.manufacturerConverter.toDTO(model);
    }

    @Override
    public void updateStatus(final Long id, final boolean status) {

        Manufacturer model;
        try {
            model = this.manufacturerRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }
        model.setStatus(status);
        this.manufacturerRepository.save(model);
    }

    @Override
    public String upload(final MultipartFile file) {
        final StringBuilder errorMsg = new StringBuilder();
        final ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedVerify(true);
        try {
            final ExcelImportResult<ManufacturerImportVO> result =
                    ExcelImportUtil.importExcelMore(file.getInputStream(), ManufacturerImportVO.class, params);
            if (result.isVerifyFail()) {
                final List<ManufacturerImportVO> failList = result.getFailList();
                failList.forEach(l -> {
                    errorMsg.append("第" + (l.getRowNum() + 1) + "行," + l.getErrorMsg() + "! \n");
                });

            }
            final List<Manufacturer> models = new ArrayList<>();
            final List<ManufacturerImportVO> saveList = result.getList();
            for (final ManufacturerImportVO vo : saveList) {
                final Manufacturer model = this.manufacturerConverter.toModel(vo);
                //                //状态
                //                if (!StringUtils.isEmpty(vo.getStatus().toString())
                //                        && vo.getStatus().toString().contains(DCAMConsts.DICTIONARY_SPLITOR)) {
                //                    final String[] status = vo.getStatus().toString().split(DCAMConsts.DICTIONARY_SPLITOR);
                //                    try {
                //                        model.setStatus(status[1].equals("1") ? true : false);
                //                    } catch (final EntityNotFoundException e) {
                //                        throw new UnitedException("状态赋值出错", new Object[] {status[0] });
                //                    }
                //                }
                models.add(model);
            }
            if (!models.isEmpty()) {
                this.manufacturerRepository.saveAll(models);
            }

        } catch (final Exception e) {
            e.printStackTrace();
            ManufacturerServiceImpl.log.error("上传失败", e);
            throw new UnitedException(e.getMessage(), new Object[] {});
        }

        return errorMsg.toString();
    }

    @Override
    public Workbook template() {
        final List<ManufacturerImportVO> list = new ArrayList<>();
        final Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("供应商导入模板", "供应商导入模板", ExcelType.XSSF),
                ManufacturerImportVO.class, list);

        //        //状态候选
        //        final List<String> status = Arrays.asList("启用_1", "禁用_0");
        //
        //        final Iterator<Sheet> iterator = workbook.iterator();
        //        while (iterator.hasNext()) {
        //            final Sheet sheet = iterator.next();
        //            EasyPoiExcelUtil.sheetConstraintXSSF(sheet, DCAMConsts.ASSET_START_CONSTRAINT_ROW,
        //                    DCAMConsts.ASSET_CONSTRAINT_ROW, 8,
        //                    8, status);
        //
        //        }
        return workbook;
    }

    @Override
    public boolean nameExisted(String name) {
        return this.manufacturerRepository.countByName(name) > 0 ? true : false;
    }

}
